﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using SharePointOfView.ExtensionMethods;
using Microsoft.SharePoint.Utilities;
using SharePointOfView.Diagnostics;

namespace SharePointOfView.Samples.ExtensionMethods
{
    /// <summary>
    /// Demonstrate the use of TryGet, DeleteItems, AddItems and DeleteUploadedFiles ExtensionMethods for SharePoint.
    /// </summary>
    class FeatureReceiver : SPFeatureReceiver
    {
        private const string SOVListName = "SharePointOfView Announcements";
        private const string logErrorCategory = "SOV.ExtMethods.FeatureReceiver";

        /// <summary>
        /// Occurs after a Feature is activated.
        /// </summary>
        /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            ULS.WriteInformation("FeatureActivated", logErrorCategory);

            SPSite site = properties.Feature.Parent as SPSite;

            SPWeb web = site.RootWeb;

            SPList SOVList = null;

            if (!web.Lists.SovTryGet(SOVListName, out SOVList))
            {
                //Create the SOV Annoucement list
                Guid guidSOVList = web.Lists.Add(SOVListName, "", "Lists/SOVAnnouncements", "00bfea71-d1ce-42de-9c63-a44004ce0104", 104, "100", SPListTemplate.QuickLaunchOptions.On);
                SOVList = web.Lists[guidSOVList];
            }
            else
                ULS.WriteInformation(string.Format("List : {0}  already exist at {1}, will use this one", SOVListName, web.Url), logErrorCategory);

            ULS.WriteInformation("Creating Items", logErrorCategory);

            //Create the data you will insert in each Items
            Dictionary<string, string> metadata = new Dictionary<string, string>();
            //If value is null then a random number will be generated at runtime
            metadata.Add("Title", null);
            metadata.Add("Body", "SharePoint Of View Announcements Body");
            string validDateTimeFormat = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now.AddDays(1));
            // We need to insert a valid dateTime with a specific format : 2008-06-01T14:02:08Z
            metadata.Add("Expires", validDateTimeFormat);

            //AddItems will throw an Exception if anything goes wrong with the call to ProcessBatchData
            try
            {
                SOVList.SovAddItems(50, metadata, false);
            }
            catch (Exception ex)
            {
                ULS.WriteError(string.Format("Message : {0}, InnerMessage : {1}, StackTrace : {2}", ex.Message, ex.InnerException, ex.StackTrace), logErrorCategory);
            }
        }

        /// <summary>
        /// Occurs when a Feature is deactivated.
        /// </summary>
        /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            ULS.WriteInformation("FeatureDeactivating", logErrorCategory);

            //Delete the uploaded files (4 Hello World Web Parts)
            ULS.WriteInformation("Delete the 4 Hello World Web Parts", logErrorCategory);
            properties.SovDeleteUploadedFiles();

            SPSite site = properties.Feature.Parent as SPSite;

            SPWeb web = site.RootWeb;

            SPList SOVList = null;

            if (web.Lists.SovTryGet(SOVListName, out SOVList))
            {
                //Delete Items in the list, the easy/quick way.
                // If you want to delete specific Item, add their ID to the dictionnary
                ULS.WriteInformation("Delete 50 Items", logErrorCategory);

                //DeleteItems will throw an Exception if anything goes wrong with the call to ProcessBatchData
                try
                {
                    SOVList.SovDeleteItems(false, null);
                }
                catch (Exception ex)
                {
                    ULS.WriteError(string.Format("Message : {0}, InnerMessage : {1}, StackTrace : {2}", ex.Message, ex.InnerException, ex.StackTrace), logErrorCategory);
                }

                //In this case, just deleting the list whould have done the job... Just another stupid example :)
                ULS.WriteInformation("Delete SharePointOfView Announcements", logErrorCategory);
                SOVList.Delete();
            }
            else
                ULS.WriteInformation(string.Format("List : {0}  didn't exist at {1}, maybe the user had previously deleted the list", SOVListName, web.Url), logErrorCategory);
        }

        #region NotImplemented
        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            //throw new NotImplementedException();
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            //throw new NotImplementedException();
        }
        #endregion


    }
}
